<template>
    <div  style="height:1500px; display: flex; flex-direction: column; overflow: hidden;">
      <el-scrollbar style="flex: 1; --el-scrollbar-bg-color: #f0f2f5;">
     <!-- 屠宰信息模块 -->
     <div class="breeding-card" style="margin-left: 0px;">
          <div class="card-header">
            <h2>屠宰信息  <el-button size="big" type="primary" @click="open()">设置</el-button></h2>
          </div>
          <div class="info-grid">
            <div class="info-row">
              <span>批次：{{ form.batch }}</span>
              <span>到厂均重：{{ form.weight }} 公斤</span>
            </div>
            <div class="info-row">
              <spa v-if="form.arrival!=null" >到厂时间：{{ moment(form.arrival).format("YYYY-MM-DD")}}</spa>
              <spa v-else >到厂时间：{{ form.arrival}}</spa>
              <span v-if="form.slaughterTime!=null">屠宰时间：{{ moment(form.slaughterTime).format("YYYY-MM-DD") }}</span>
              <span  v-else>屠宰时间：{{ form.slaughterTime }}</span>
            </div>
          </div>
        </div>

        <!-- 相关资质图片 -->
    <div style="margin-top: 50px ;margin-left: 20px;"class="breeding-card" >
        <h2>相关资质</h2>
        <!-- 图片容器 -->
  <div style="display: flex; align-items: flex-start; gap: 25px; margin-left: 20px;">
    <!-- 上传区域 -->
    <div style="display: flex; flex-direction: column; gap: 15px;">
      <el-upload
        v-model:file-list="fileList"
        action="http://localhost:5013/api/Pic/UploadImage/upload"
        :data="{ picType: 111, batch: route.query.batch }"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove">
        <el-icon><Plus /></el-icon>
      </el-upload>
      <div style="color: #666; font-size: 14px;">
      </div>
    </div>
  </div>

  </div>
<!-- 企业信息 -->
  <div style="margin-top: 50px;margin-left: 20px;" class="breeding-card" >
        <h2>企业信息  <el-button size="big" type="primary" @click="open1()">设置</el-button></h2>
       
  
    <div class="info-grid"  style="margin-left: 20px;">
            <div class="info-row">
              <span>公司名称：{{ enterads.slaName }}</span>
              <span v-if="enterads.estabTime>100">成立时间：{{ moment(enterpe.estabTime).format("YYYY-MM-DD")}}</span>
              <span v-else>成立时间：{{enterpe.estabTime}}</span>
            </div>
            <div class="info-row">
              <span>公司地址：{{ enterads.corAddr }}</span>
            </div>
            <div class="info-row">
              <span>公司简介：{{ enterads.jianjie }}</span>
            </div>
          </div>
          </div>

        <!--企业照片 -->
        <div style="margin-top: 50px;margin-left: 20px; "  class="breeding-card" >
        <h2>企业照片</h2>
  
        <!-- 图片容器 -->
  <div style="display: flex; align-items: flex-start; gap: 25px;margin-left: 20px;">    
    <!-- 上传区域 -->
    <div style="display: flex; flex-direction: column; gap: 15px;">
      <el-upload
        v-model:file-list="fileList1"
        action="http://localhost:5013/api/Pic/UploadImage/upload"
        :data="{ picType: 105, batch: route.query.batch }"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove">
        <el-icon><Plus /></el-icon>
      </el-upload>
      <div style="color: #666; font-size: 14px;">
      </div>
    </div>
 
  </div> </div>

</el-scrollbar>
</div>
<!-- 企业信息弹框 -->
<el-dialog v-model="dialogFormVisible1" title="企业信息" width="500">
    <el-form :model="enterpe">
      <el-form-item label="公司名称">
        <el-input v-model="enterpe.slaName" autocomplete="off" />
      </el-form-item>

      <el-form-item label="公司地址">
        <div id="app">
    <el-cascader
      size="large"
      :options="pcaTextArr"
      v-model="selectedOptions"></el-cascader>
  </div>
      </el-form-item>

      <el-form-item label="成立时间" >
        <el-input type="date" v-model="enterpe.estabTime"  value-format="YYYY-MM-DD" autocomplete="off" />
      </el-form-item>

      <el-form-item label="公司简介">
        <el-input type="textarea" v-model="enterpe.jianjie" autocomplete="off" />
      </el-form-item>
      
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible1 = false">取消</el-button>
        <el-button type="primary" @click="updateenter()">确认</el-button>
      </div>
    </template>
  </el-dialog>



<!-- 屠宰信息弹窗 -->
    <el-dialog v-model="dialogFormVisible" title="屠宰信息" width="500">
    <el-form :model="form">
      <el-form-item label="批次" :label-width="formLabelWidth">
        <el-input v-model="form.batch" autocomplete="off" />
      </el-form-item>

      <el-form-item label="到厂均重" :label-width="formLabelWidth">
        <el-input v-model="form.weight" autocomplete="off" />
      </el-form-item>

      <el-form-item label="到厂时间" :label-width="formLabelWidth">
        <el-date-picker  v-model="form.arrival"type="date"format="YYYY/MM/DD"value-format="YYYY-MM-DD"/>
      </el-form-item>

      <el-form-item label="屠宰时间" :label-width="formLabelWidth">
        <el-date-picker  v-model="form.slaughterTime"type="date"format="YYYY/MM/DD"value-format="YYYY-MM-DD"/>
      </el-form-item>
      
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="AddBreed()">确认</el-button>
      </div>
    </template>
  </el-dialog>

</template>

<script setup lang="ts">
  import type { ImageProps } from 'element-plus';
  import { ref, reactive, onMounted,watch  } from 'vue';
  import moment, { isDate } from 'moment'
  import axios from 'axios';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { useCounterStore } from '@/stores/counter';
  import { useRouter, useRoute } from 'vue-router';
  import type { UploadProps, UploadUserFile } from 'element-plus';
  import { regionData } from 'element-china-area-data'

import { pcaTextArr } from 'element-china-area-data'
import { ElCascader } from 'element-plus'
let route=useRoute();
const selectedOptions = ref([])
// 级联选择器配置
const cascaderProps = {
  value: 'code',
  label: 'name',
  children: 'children'
}
  const tableData =ref([])
  const dialogFormVisible = ref(false)
  const dialogFormVisible1 = ref(false)
const formLabelWidth = '140px'

// 打开弹窗时初始化数据
const open1 = async () => {
  await getenter()
  dialogFormVisible1.value = true
}



//存储企业信息变量
const enterads=ref([]);
//查询企业信息
const getenter=()=>{
    axios({
        url:'http://localhost:5011/api/Product/QueryEnter',
        method:'get',
        params:{
          Batch:route.query.batch
        }
    })
    .then(res=>{
        try{
            if(res.data.code==101){
            enterads.value=res.data.data;
            console.log('屠宰企业信息',enterads.value)
            enterpe.entId=res.data.data.entId
            enterpe.entName=res.data.data.entName
            enterpe.personName=res.data.data.personName
            enterpe.quantity=res.data.data.quantity
            enterpe.slaName=res.data.data.slaName
            enterpe.supName=res.data.data.supName
            enterpe.estabTime=res.data.data.estabTime?.split('T')[0] || ''
            if(enterpe.estabTime==="0001-01-01"){
              enterpe.estabTime='';
            }
            
            enterpe.corAddr=res.data.data.corAddr
            enterpe.license=res.data.data.license
            const addressCodes = convertAddressToCodes(res.data.data.corAddr)
            selectedOptions.value = addressCodes
            enterpe.sheng=res.data.data.sheng
            enterpe.shi=res.data.data.shi
            enterpe.xian =res.data.data.xian
            selectedOptions.value=res.data.data.corAddr
            enterpe.batch=res.data.data.batch
            enterpe.jianjie=res.data.data.jianjie
            console.log('成立时间',enterpe.estabTime);
            getSheng(enterpe.sheng, enterpe.shi,enterpe.xian);
        }
       
        }catch{

        }
        
        // 设置地址选择器值
     
    })
}

const getSheng=(ids1:any,ids2:any,ids3:any)=>{
    selectedOptions.value=[ids1.toString(),ids2.toString(),ids3.toString()];
console.log('qiyedizhi',selectedOptions.value);
}
// 新增地址编码转换函数
const convertAddressToCodes = (addressStr: string) => {
  const addressParts = addressStr.split('/')
  return addressParts.map(part => {
    const found = pcaTextArr.find(p => p.name === part)
    return found ? found.code : ''
  })
}
// 企业所需数据
const enterpe=reactive({
    entId:2,
    entName:'',
    personName:'',
    quantity:'',
    slaName:'',
    supName:'',
    estabTime:'',
    corAddr:'',
    license:'',
    batch:'',
    sheng:selectedOptions.value[0],
    shi:selectedOptions.value[1],
    xian:selectedOptions.value[2],
    jianjie:''
})
//添加企业信息方法
const updateenter=()=>{
    console.log('屠宰企业省',selectedOptions.value[0])
    console.log('屠宰企业市',selectedOptions.value[1])
    console.log('屠宰企业县',selectedOptions.value[2])
    console.log('屠宰企业县',selectedOptions)
    console.log('屠宰企业信息',enterpe)
 // 手动确保地址信息同步
 if (selectedOptions.value.length === 3) {
    enterpe.sheng = selectedOptions.value[0]
    enterpe.shi = selectedOptions.value[1]
    enterpe.xian = selectedOptions.value[2]
  }
    axios({
        url:'http://localhost:5013/api/Shop/UpdateEnter',
        method:'put',
        data:enterpe
    })
    .then(res=>{
        if(res.data.code==101){
            
            ElMessage.success("操作成功");
            dialogFormVisible1.value=false;
            getenter()
        }
    })
}
//生命周期钩子函数
onMounted(()=>{
    getbreedlist();
    selePic2();
    selePic4();
    getenter();
    getSlaAll()
})

const poiuyt2=ref([]);
//查询屠宰模块信息完成度
  const getSlaAll=()=>{
    axios({
      url:'http://localhost:5011/api/Product/QuerySlaAll',
      method:'get',
      params:{
        ProId:route.query.proId,
        Batch:route.query.batch      }
    }).then(res=>{
      if(res.data.code==101){
        poiuyt2.value=res.data.data
        console.log('屠宰信息完成度',poiuyt2.value)
      }
    })
  }

// 监听省市区变化自动更新表单字段
watch(selectedOptions, (newVal) => {
  const [province = '', city = '', area = ''] = newVal
  enterpe.sheng = province
  enterpe.shi = city
  enterpe.xian = area
})
// 屠宰所需数据
const form = reactive({
    batch: '',
    weight: '',
    arrival: '',
    slaughterTime: ''
})
//添加屠宰信息弹窗
const open=()=>{
    dialogFormVisible.value=true;
}
//添加屠宰信息方法
const AddBreed=()=>{
    axios({
        url:'http://localhost:5013/api/Shop/AddSlaughter',
        method:'post',
        data:form
    })
    .then(res=>{
        if(res.data.code==101){
            ElMessage.success('操作成功');
            dialogFormVisible.value=false; 
            getbreedlist();
        }
    })
}
//存储屠宰信息数据变量
const breedsc=ref([]);
//查询屠宰信息方法
const getbreedlist=()=>{
    axios({
        url:'http://localhost:5011/api/Product/QuerySlaughter',
        method:'get',
        params:{
          Batch:route.query.batch
        }
    })
    .then(res=>{
        if(res.data.code==101){
            breedsc.value=res.data.data
            form.batch=res.data.data.batch
            form.weight=res.data.data.weight
            form.arrival=res.data.data.arrival
            form.slaughterTime=res.data.data.slaughterTime
        }
    })
}

//图片所需数据
const fileList = ref<UploadUserFile[]>([]);
  const fileList1 = ref<UploadUserFile[]>([]);
const dialogImageUrl = ref('');
  const dialogVisible = ref(false);
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    console.log('删除图片数据第一个',uploadFile.name);
    console.log('删除图片数据第二', uploadFiles);
    deletepic(uploadFile.name);
  };
  
  const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!;
    dialogVisible.value = true;
  };
//删除图片
const deletepic=(pictrueId:any)=>{
  axios({
    url:'http://localhost:5013/api/Pic/DeletePic',
    method:'put',
    data:{
      pictureId:pictrueId
    }
  })
  .then(res=>{
    if(res.data.code==101){
      ElMessage.success("操作成功");
    }
  })
}

    // 查询图片
    const syoo = reactive({
    PicType: 111,
    Batch: route.query.batch
  });
  // 查询图片宰前检疫
  const selePic2 = () => {
  axios.get('http://localhost:5013/api/Pic/QueryPic', {
    params: { PicType: syoo.PicType, Batch: syoo.Batch }
  }).then(res => {
    if (res.data.code == 101) {
      fileList.value = res.data.list.map((item:any) => ({
        name: item.pictureId.toString(),
        url: `${item.pictureAddr}`,
        status: 'success'
      }));
    }
  }).catch(error => {
    console.error('请求失败:', error);0
  });
};
  


      // 查询图片屠宰企业图片
  const selePic4 = () => {
  axios.get('http://localhost:5013/api/Pic/QueryPic', {
    params: { PicType: 105, Batch: syoo.Batch }
  }).then(res => {
    if (res.data.code == 101) {
      fileList1.value = res.data.list.map((item:any) => ({
        name: item.pictureId.toString(),
        url: `${item.pictureAddr}`,
        status: 'success'
      }));
    }
  }).catch(error => {
    console.error('请求失败:', error);0
  });
};

</script>

<style scoped>
  .full-container {
    height: 100vh;
    overflow: hidden;
    background: #f0f2f5;
  }
  
  .nav-bar {
    height: 48px;
    background: #545c64;
    display: flex;
    align-items: center;
    padding: 0 20px;
  }
  
  .nav-item {
    color: white;
    margin-right: 40px;
    cursor: pointer;
  }
  
  .main-content {
    height: calc(100vh - 48px);
    padding: 20px;
    overflow: auto;
  }
  
  .breeding-card,
  .healthcare-card {
    background: white;
    border-radius: 4px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
  }
  
  .info-grid {
    display: grid;
    gap: 16px;
  }
  
  .info-row {
    display: flex;
    gap: 40px;
    padding: 8px 0;
  }
  
  .data-table {
    margin-top: 16px;
  }
  
  .action-group {
    display: flex;
    gap: 12px;
  }
  
  .new-form {
    margin-top: 16px;
    padding: 16px;
    background: #fafafa;
    border-radius: 4px;
  }
  
  .form-actions {
    margin-top: 12px;
    display: flex;
    gap: 12px;
  }
  </style>
  <style scoped>


  /* 按钮样式统一 */
  .el-button {
    border-radius: 4px;
    padding: 8px 15px;
  }
  </style>